﻿using CarPCBATest.Procedure;
using Common;
using Device;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using MoreLinq;
using NLog.Fluent;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Xml;
using VM.Core;
using VM.PlatformSDKCS;
using VMControls.WPF.Release;
using WebServiceTool.WebReference1;

namespace CarPCBATest.ViewModel
{
    public partial class HomeViewModel : NotifyBase
    {
        public Action SNInputFocusAction;
        public Action<int> SNInputFocusSwitchAction;

        //public Action<int> SNInputVisibilityAction;
        public Action<PcbConfig> ConfigChangedAction;

        private bool vmPorjLoaded = false;
        public List<Product> Products { get; set; }
        public List<string> LocalLogs { get; set; }

        public STD_IN STD_IN { get; set; } = new STD_IN();
        public StarnetService WebClient { get; set; } = new StarnetService();

        private void ShowMessage(string msg, string msgType = "错误")
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var mwin = Application.Current.MainWindow as MetroWindow;

                mwin.ShowMessageAsync(msgType, msg);
            });
        }

        private bool? _testResult;

        public bool? TestResult
        {
            get { return _testResult; }
            set
            {
                _testResult = value;
                this.DoNotify();
            }
        }

        public HomeViewModel()
        {
            ResetCountCommand = new CommandBase(ResetCount);
            SaveImageCommand = new CommandBase(SaveImage);
            StartCommand = new CommandBase(Start);
            ResetCommand = new CommandBase(Reset);
            LoadedCommand = new CommandBase(Loaded);
            UnloadedCommand = new CommandBase(Unloaded);
            TestResult = null;

            VmSolution.OnWorkStatusEvent += VmSolution_OnWorkStatusEvent;//工作执行状态回调
            VmSolution.OnSolutionLoadEndEvent += VmSolution_OnSolutionLoadEndEvent;
            VmSolution.OnSolutionLoadBeginEvent += VmSolution_OnSolutionLoadBeginEvent;

            MachineStatus = MachineStatus.Stop;
            IOModule.StartAction += StartAction;
            IOModule.EmgStopAction += EmgStopAction;
            IOModule.EmgCancelAction += EmgCancelAction;
            PcbConfigHelper.Load();
            OKCount = PcbConfigHelper.AllPcbConfig.OKCount;
            NGCount = PcbConfigHelper.AllPcbConfig.NGCount;
        }

        private void ResetCount(object obj)
        {
            OKCount = 0;
            NGCount = 0;
        }

        private void VmSolution_OnSolutionLoadBeginEvent(ImvsSdkDefine.IMVS_SOLUTION_LOAD_BEGEIN_INFO solutionLoadBeginInfo)
        {
            vmPorjLoaded = false;
        }

        private void VmSolution_OnSolutionLoadEndEvent(ImvsSdkDefine.IMVS_SOLUTION_LOAD_END_INFO solutionLoadEndInfo)
        {
            try
            {
                if (solutionLoadEndInfo.nStatus == 0)
                {
                    Stopwatch sw = Stopwatch.StartNew();
                    VmSolution.Instance.SilentExecute();
                    Console.WriteLine(sw.Elapsed.Seconds);
                }
            }
            catch (VmException vex)
            {
                Mylog.Error(vex, vex.Message);
                Log = vex.Message;
            }
            vmPorjLoaded = true;
        }

        private void SaveImage(object obj)
        {
            try
            {
                currentProcId = 10003;
                Stopwatch sw = Stopwatch.StartNew();
                for (int i = 0; i < 30; i++)
                {
                    Log = $"save[{i}]";
                    vmProcHaveExec = false;
                    VisionTool.RunProc("SaveImage");
                    while (!vmProcHaveExec) ;
                    Console.WriteLine("视觉执行耗时：" + sw.ElapsedMilliseconds);
                }
            }
            catch (Exception ex)
            {
                Log = ex.Message;
            }
        }

        private void EmgCancelAction()
        {
            switch (MachineStatus)
            {
                case MachineStatus.Running:
                    break;

                case MachineStatus.Stop:
                    break;

                case MachineStatus.EmgStop:
                    MachineStatus = MachineStatus.Stop;
                    break;

                default:
                    break;
            }
        }

        private void EmgStopAction()
        {
            switch (MachineStatus)
            {
                case MachineStatus.Running:
                    MachineStatus = MachineStatus.EmgStop;
                    break;

                case MachineStatus.Stop:
                    MachineStatus = MachineStatus.EmgStop;
                    break;

                case MachineStatus.EmgStop:
                    break;

                default:
                    break;
            }
        }

        private void StartAction()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                Start(null);
            });
        }

        private PcbConfig _pcbConfig;

        public PcbConfig PcbConfig
        {
            get { return _pcbConfig; }
            set
            {
                if (value != null)
                {
                    VisionProjPath = value.VisionProjPath;
                }
                _pcbConfig = value;
                this.DoNotify();
            }
        }

        private string _visionProjPath;

        public string VisionProjPath
        {
            get { return _visionProjPath; }
            set
            {
                if (value != _visionProjPath & value != null)
                {
                    Log = $"加载视觉方案";
                    if (File.Exists(value))
                    {
                        Task.Run(() =>
                        {
                            try
                            {
                                VisionTool.LoadVMSolution(value);
                                Log = "加载视觉方案成功";
                                vmPorjLoaded = true;
                            }
                            catch (Exception ex)
                            {
                                Log = ex.Message;
                            }
                        });
                    }
                    else
                    {
                        Log = $"视觉方案不存在[{value}]!";
                    }
                }
                _visionProjPath = value;
                this.DoNotify();
            }
        }

        private void Loaded(object obj)
        {
            var config = PcbConfigHelper.AllPcbConfig;
            if (config != null)
            {
                PcbConfig = config.ListConfig.Where(t => t.No == config.UsingNo).ToList()[0];
                this.ConfigChangedAction?.Invoke(PcbConfig);
                var stations = PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList();
                DcStationNoWithSNIndex = new Dictionary<int, int>();
                for (int i = 0; i < stations.Count(); i++)
                {
                    DcStationNoWithSNIndex.Add(stations[i].StationNo, i);
                }
            }
            this.SNInputFocusSwitchAction?.Invoke(0);

            //if (config is not null)
            //{
            //    WebClient.Url = config.WebServiceUrl;
            //}
            //if (PcbConfig is not null)
            //{
            //    var stationCount = PcbConfig.ListSingBoardConfig.Count;
            //SNInputVisibilityAction.Invoke(stationCount);
            //}

            Task.Run(() =>
            {
                try
                {
                    var titile = PcbConfigHelper.Load().Title;
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        var mwin = Application.Current.MainWindow as MetroWindow;
                        mwin.Title = titile;
                    });

                    DM3058E.Connect(config.DM3025EPort);
                    DM3058E.SetFunction(Function.DCI);
                    //IT6302A.Connect();
                    IV_3003T.Connect(config.IV3003TPort);
                    IV_3003T.Init();
                    IOModule.Connect();
                    IOModuleDO.Connect();
                }
                catch (Exception ex)
                {
                    Log = ex.Message;
                    Mylog.Error(ex, ex.Message);
                }
            });
        }

        private void Unloaded(object obj)
        {
        }

        private void Reset(object obj)
        {
            try
            {
                SN0 = "";
                SN1 = "";
                SN2 = "";
                SN3 = "";
                SN4 = "";
                SN5 = "";
                SN6 = "";
                SN7 = "";
                SN8 = "";
                SN9 = "";
                SN0UploadMesResult = null;
                SN1UploadMesResult = null;
                SN2UploadMesResult = null;
                SN3UploadMesResult = null;
                SN4UploadMesResult = null;
                SN5UploadMesResult = null;
                SN6UploadMesResult = null;
                SN7UploadMesResult = null;
                SN8UploadMesResult = null;
                SN9UploadMesResult = null;

                this.SNInputFocusSwitchAction.Invoke(0);
                //DM3058E.Connect();
                //IT6302A.Connect();
                //IOModule.Connect();
                AirReset();
                //IOModule.SetDOValue(DODefine.AirReset, 0);
                //IOModule.SetDOValue(DODefine.Power, 0);
                //IOModule.SetDOValue(DODefine.NG, 0);

                IOModuleDO.SetDOValue(DODefine.GreenLed, 0);
                IOModuleDO.SetDOValue(DODefine.YellowLed, 1);
                IOModuleDO.SetDOValue(DODefine.RedLed, 0);
                TestResult = null;

                Log = "复位完成";
            }
            catch (Exception ex)
            {
                Log = ex.Message;
            }
        }

        private string _sn0;

        public string SN0
        {
            get { return _sn0; }
            set
            {
                _sn0 = value;
                this.DoNotify();

                if (PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList().Count > 1)
                {
                    if (_sn0.Length >= PcbConfig.ListSingBoardConfig[0].SNLength)
                        SNInputFocusSwitchAction?.Invoke(1);
                }
            }
        }

        private bool? _sn0UploadMesResult;

        public bool? SN0UploadMesResult
        {
            get { return _sn0UploadMesResult; }
            set
            {
                _sn0UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn1UploadMesResult;

        public bool? SN1UploadMesResult
        {
            get { return _sn1UploadMesResult; }
            set
            {
                _sn1UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn2UploadMesResult;

        public bool? SN2UploadMesResult
        {
            get { return _sn2UploadMesResult; }
            set
            {
                _sn2UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn3UploadMesResult;

        public bool? SN3UploadMesResult
        {
            get { return _sn3UploadMesResult; }
            set
            {
                _sn3UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn4UploadMesResult;

        public bool? SN4UploadMesResult
        {
            get { return _sn4UploadMesResult; }
            set
            {
                _sn4UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn5UploadMesResult;

        public bool? SN5UploadMesResult
        {
            get { return _sn5UploadMesResult; }
            set
            {
                _sn5UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn6UploadMesResult;

        public bool? SN6UploadMesResult
        {
            get { return _sn6UploadMesResult; }
            set
            {
                _sn6UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn7UploadMesResult;

        public bool? SN7UploadMesResult
        {
            get { return _sn7UploadMesResult; }
            set
            {
                _sn7UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn8UploadMesResult;

        public bool? SN8UploadMesResult
        {
            get { return _sn8UploadMesResult; }
            set
            {
                _sn8UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn9UploadMesResult;

        public bool? SN9UploadMesResult
        {
            get { return _sn9UploadMesResult; }
            set
            {
                _sn9UploadMesResult = value;
                this.DoNotify();
            }
        }

        private string _sn1;

        public string SN1
        {
            get { return _sn1; }
            set
            {
                _sn1 = value;
                this.DoNotify();

                if (PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList().Count > 2)
                {
                    if (_sn1.Length >= PcbConfig.ListSingBoardConfig[1].SNLength)
                        SNInputFocusSwitchAction?.Invoke(2);
                }
            }
        }

        private string _sn2;

        public string SN2
        {
            get { return _sn2; }
            set
            {
                _sn2 = value;
                this.DoNotify();
                if (PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList().Count > 3)
                {
                    if (_sn2.Length >= PcbConfig.ListSingBoardConfig[2].SNLength)
                        SNInputFocusSwitchAction?.Invoke(3);
                }
            }
        }

        private string _sn3;

        public string SN3
        {
            get { return _sn3; }
            set
            {
                _sn3 = value;
                this.DoNotify();
                if (PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList().Count > 4)
                {
                    if (_sn3.Length >= PcbConfig.ListSingBoardConfig[3].SNLength)
                        SNInputFocusSwitchAction?.Invoke(4);
                }
            }
        }

        private string _sn4;

        public string SN4
        {
            get { return _sn4; }
            set
            {
                _sn4 = value;
                this.DoNotify();
                if (PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList().Count > 5)
                {
                    if (_sn4.Length >= PcbConfig.ListSingBoardConfig[4].SNLength)
                        SNInputFocusSwitchAction?.Invoke(5);
                }
            }
        }

        private string _sn5;

        public string SN5
        {
            get { return _sn5; }
            set
            {
                _sn5 = value;
                this.DoNotify();
                if (PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList().Count > 6)
                {
                    if (_sn5.Length >= PcbConfig.ListSingBoardConfig[5].SNLength)
                        SNInputFocusSwitchAction?.Invoke(6);
                }
            }
        }

        private string _sn6;

        public string SN6
        {
            get { return _sn6; }
            set
            {
                _sn6 = value;
                this.DoNotify();
                if (PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList().Count > 7)
                {
                    if (_sn6.Length >= PcbConfig.ListSingBoardConfig[6].SNLength)
                        SNInputFocusSwitchAction?.Invoke(7);
                }
            }
        }

        private string _sn7;

        public string SN7
        {
            get { return _sn7; }
            set
            {
                _sn7 = value;
                this.DoNotify();
                if (PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList().Count > 8)
                {
                    if (_sn7.Length >= PcbConfig.ListSingBoardConfig[7].SNLength)
                        SNInputFocusSwitchAction?.Invoke(8);
                }
            }
        }

        private string _sn8;

        public string SN8
        {
            get { return _sn8; }
            set
            {
                _sn8 = value;
                this.DoNotify();
                if (PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList().Count > 9)
                {
                    if (_sn8.Length >= PcbConfig.ListSingBoardConfig[8].SNLength)
                        SNInputFocusSwitchAction?.Invoke(9);
                }
            }
        }

        private string _sn9;

        public string SN9
        {
            get { return _sn9; }
            set
            {
                _sn9 = value;
                this.DoNotify();
            }
        }

        private int _okCount;

        public int OKCount
        {
            get { return _okCount; }
            set
            {
                _okCount = value;

                if (NGCount + value > 0)
                {
                    OKRate = Math.Round(100 * (OKCount) / ((double)(NGCount + value)), 2).ToString() + "%";
                }
                else
                {
                    OKRate = "";
                }
                this.DoNotify();
            }
        }

        private int _ngCount;

        public int NGCount
        {
            get { return _ngCount; }
            set
            {
                _ngCount = value;
                if (OKCount + value > 0)
                {
                    OKRate = Math.Round(100 * (OKCount) / ((double)(OKCount + value)), 2).ToString() + "%";
                }
                else
                {
                    OKRate = "";
                }
                this.DoNotify();
            }
        }

        private string _okRate;

        public string OKRate
        {
            get { return _okRate; }
            set
            {
                _okRate = value;
                this.DoNotify();
            }
        }

        private MachineStatus _machineStatus;

        public MachineStatus MachineStatus
        {
            get { return _machineStatus; }
            set { _machineStatus = value; }
        }

        private int count = 0;
        public VmRenderControl control;

        private void SaveXmlToFile(string xmlString, string filePath)
        {
            try
            {
                // 创建 XmlDocument 对象并加载 XML 字符串
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xmlString);

                // 保存 XML 文档到文件
                xmlDoc.Save(filePath);
            }
            catch (Exception ex)
            {
                Mylog.Error(ex, ex.Message);
                throw ex;
            }
        }

        private Dictionary<int, int> DcStationNoWithSNIndex;

        private void Start(object obj)
        {
            //Log = "error!";
            // 0 系统状态判定
            switch (MachineStatus)
            {
                case MachineStatus.Running:
                    return;

                case MachineStatus.Stop:
                    if (!IOModule.GetDIValue(DIDefine.SafeLight))
                    {
                        Log = "安全光栅感应";
                        //IOModule.SetDOValue(DODefine.NG, 1);
                        return;
                    }
                    MachineStatus = MachineStatus.Running;
                    break;

                case MachineStatus.EmgStop:
                    Log = "设备处于急停状态";
                    //IOModule.SetDOValue(DODefine.NG, 1);
                    return;

                default:
                    return;
            }

            Task.Run(() =>
            {
                try
                {
                    TestResult = null;

                    SN0UploadMesResult = null;
                    SN1UploadMesResult = null;
                    SN2UploadMesResult = null;
                    SN3UploadMesResult = null;
                    SN4UploadMesResult = null;
                    SN5UploadMesResult = null;
                    SN6UploadMesResult = null;
                    SN7UploadMesResult = null;
                    SN8UploadMesResult = null;
                    SN9UploadMesResult = null;

                    Log = "------------------" + count++.ToString();
                    if (PcbConfig is null)
                    {
                        throw new Exception("测试方案不能为空!");
                    }
                    //int stationCount = PcbConfig.StationCount;
                    //int snLength = PcbConfig.SNLength;

                    #region 参数校验

                    // 探针使用次数校验
                    if (PcbConfig.ProbeMaxUsedTimes < PcbConfig.ProbeUsedTimes)
                    {
                        throw new Exception("探针使用次数超过预设值!");
                    }

                    #endregion 参数校验

                    var stations = PcbConfig.ListSingBoardConfig.DistinctBy(x => x.StationNo).ToList();

                    #region SN校验

                    for (int i = 0; i < stations.Count(); i++)
                    {
                        Type classType = typeof(HomeViewModel);
                        var propertyInfo = classType.GetProperty($"SN{i}");
                        if (stations[i].SNLength != propertyInfo.GetValue(this).ToString().Length)
                        {
                            throw new Exception($"工位[{stations[i].StationNo}]SN长度异常!");
                        }

                        if (!(stations[i].Pattern is null) && !Regex.IsMatch(propertyInfo.GetValue(this).ToString(), stations[i].Pattern))
                        {
                            throw new Exception($"工位[{stations[i].StationNo}]SN不匹配!");
                        }
                    }

                    #endregion SN校验

                    bool result = false;
                    for (int m = 0; m < 2; m++)
                    {
                        if (!vmPorjLoaded)
                        {
                            Log = "请等待视觉方案加载完成";
                            MachineStatus = MachineStatus.Stop;

                            this.SNInputFocusSwitchAction.Invoke(0);
                            return;
                        }

                        Products = new List<Product>();

                        #region IO 初始化

                        IOModuleDO.SetDOValue(DODefine.GreenLed, 1);
                        IOModuleDO.SetDOValue(DODefine.YellowLed, 0);
                        IOModuleDO.SetDOValue(DODefine.RedLed, 0);

                        #endregion IO 初始化

                        {
                            //1 气缸下压
                            AirWork();
                        }

                        // 更新探针使用次数
                        PcbConfig.ProbeUsedTimes += 1;
                        PcbConfigHelper.AllPcbConfig.ListConfig.Where(x => x.No == PcbConfig.No).ToArray()[0].ProbeUsedTimes = PcbConfig.ProbeUsedTimes;
                        PcbConfigHelper.Save();

                        #region 电流视觉测试逻辑

                        for (int i = 0; i < PcbConfig.ListSingBoardConfig.Count; i++)
                        {
                            Type classType = typeof(HomeViewModel);
                            var propertyInfo = classType.GetProperty($"SN{DcStationNoWithSNIndex[PcbConfig.ListSingBoardConfig[i].StationNo]}");
                            //LocalLogs.Add($"工位{i}SN={propertyInfo.GetValue(this).ToString()}");
                            Products.Add(new Product
                            {
                                SN = propertyInfo.GetValue(this).ToString(),
                                StationIndex = i + 1
                            });
                        }

                        int testIndex = 0;
                        foreach (var item in PcbConfig.ListSingBoardConfig)
                        {
                            Type classType = typeof(HomeViewModel);
                            MethodInfo methodInfo = classType.GetMethod(item.TestMethodName);
                            if (methodInfo == null)
                                throw new Exception($"测试方法未找到[{item.TestMethodName}]!");

                            methodInfo.Invoke(this, new object[] { item, testIndex++ });
                        }

                        #endregion 电流视觉测试逻辑

                        result = Products.Exists(x => x.IsOk == false);

                        // 设置电源IO
                        for (int i = 0; i < PcbConfig.ListSingBoardConfig[0].ListDOConfig.Count; i++)
                        {
                            IOModuleDO.SetDOValue((DODefine)PcbConfig.ListSingBoardConfig[0].ListDOConfig[i].DOFunction, 0);
                        }
                        Thread.Sleep(400);

                        AirReset();
                        Thread.Sleep(1500);
                        if (!result)
                        {
                            break;
                        }
                        Log = "开始复测";
                    }

                    if (!result)
                    {
                        OKCount++;
                        Log = "测试OK";
                        TestResult = true;
                        IOModuleDO.SetDOValue(DODefine.GreenLed, 0);
                        IOModuleDO.SetDOValue(DODefine.YellowLed, 1);
                        IOModuleDO.SetDOValue(DODefine.RedLed, 0);
                    }
                    else
                    {
                        NGCount++;
                        IOModuleDO.SetDOValue(DODefine.RedLed, 1);
                        IOModuleDO.SetDOValue(DODefine.GreenLed, 0);
                        IOModuleDO.SetDOValue(DODefine.YellowLed, 0);
                        Log = "测试NG!";
                        TestResult = false;
                    }

                    // 记录本地日志
                    {
                        string directory = Environment.CurrentDirectory + $"\\Data\\{DateTime.Now.ToString("yyyMMdd")}";
                        if (!Directory.Exists(directory))
                        {
                            Directory.CreateDirectory(directory);
                        }
                        string file = directory + "\\" + SN0 + "-" + DateTime.Now.ToString("yyyMMddHHmmss") + ".csv";
                        if (File.Exists(file))
                        {
                            File.Delete(file);
                        }

                        using (StreamWriter writer = new StreamWriter(file))
                        {
                            // 写入标题行
                            writer.WriteLine("功能,SN,测试结果,实测电流,标准值,NG原因");

                            // 写入数据行
                            for (int i = 0; i < Products.Count; i++)
                            {
                                string tmp = $"{PcbConfig.ListSingBoardConfig[i].LedDesc},{Products[i].SN},{Products[i].IsOk},{Products[i].TestCurrent},{Products[i].StdCurrent}";
                                if (!Products[i].IsOk)
                                {
                                    foreach (var item in Products[i].NGMessages)
                                    {
                                        tmp += $",{item}";
                                    }
                                }
                                writer.WriteLine(tmp);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    IOModuleDO.SetDOValue(DODefine.GreenLed, 0);
                    IOModuleDO.SetDOValue(DODefine.YellowLed, 0);
                    IOModuleDO.SetDOValue(DODefine.RedLed, 1);
                    Log = ex.Message + "!";
                    TestResult = false;
                    Mylog.Error(ex, ex.Message);
                }
                finally
                {
                    PcbConfigHelper.AllPcbConfig.OKCount = OKCount;
                    PcbConfigHelper.AllPcbConfig.NGCount = NGCount;

                    //PcbConfigHelper.AllPcbConfig.ListConfig.Where(x => x.No == PcbConfig.No).ToArray()[0].ProbeUsedTimes = PcbConfig.ProbeUsedTimes;
                    PcbConfigHelper.Save();

                    SN0 = "";
                    SN1 = "";
                    SN2 = "";
                    SN3 = "";
                    SN4 = "";
                    SN5 = "";
                    SN6 = "";
                    SN7 = "";
                    SN8 = "";
                    SN9 = "";
                    Thread.Sleep(100);
                    IV_3003T.SetChStatus(1);    //关闭电源

                    // 设置电源IO
                    for (int i = 0; i < PcbConfig.ListSingBoardConfig[0].ListDOConfig.Count; i++)
                    {
                        IOModuleDO.SetDOValue((DODefine)PcbConfig.ListSingBoardConfig[0].ListDOConfig[i].DOFunction, 0);
                    }

                    //IOModule.SetDOValue(DODefine.Power, 0);

                    Thread.Sleep(100);
                    //IOModuleDO.SetDOValue(DODefine.AirReset, 0);

                    ////Log = "气缸复位";
                    //IOModule.SetDOValue(DODefine.SwitchBurnMode, 0);
                    this.SNInputFocusSwitchAction.Invoke(0);
                    CameraTool.Close();
                    MachineStatus = MachineStatus.Stop;
                }
            });
        }

        private void AirReset()
        {
            IOModuleDO.SetDOValue(DODefine.AirReset, 0);
            bool timeOut1 = false;
            // 等待气缸到位
            Task.Run(() =>
            {
                Thread.Sleep(5000);
                timeOut1 = true;
            });
            while (true)
            {
                if (!IOModule.GetDIValue(DIDefine.SafeLight))
                {
                    Log = "安全光幕触发!";
                    Mylog.Info(Log);
                }
                if (MachineStatus == MachineStatus.EmgStop)
                {
                    IOModuleDO.SetDOValue(DODefine.AirReset, 0);
                    Log = "急停触发!";
                    Mylog.Info(Log);
                }
                if (!IOModule.GetDIValue(DIDefine.AirWork))
                {
                    break;
                }
                if (timeOut1)
                {
                    break;
                }
                Thread.Sleep(100);
            }
            if (timeOut1)
            {
                Log = "等待气缸复位超时!";
            }
            Log = "气缸复位";
        }

        private void AirWork()
        {
            {
                //1 气缸下压
                IOModuleDO.SetDOValue(DODefine.AirReset, 1);
                bool timeOut1 = false;
                // 等待气缸到位
                Task.Run(() =>
                {
                    Thread.Sleep(5000);
                    timeOut1 = true;
                });
                while (true)
                {
                    if (!IOModule.GetDIValue(DIDefine.SafeLight))
                    {
                        IOModuleDO.SetDOValue(DODefine.AirReset, 0);
                        Mylog.Info("安全光幕触发!");
                        throw new Exception("安全光幕触发!");
                    }
                    if (MachineStatus == MachineStatus.EmgStop)
                    {
                        IOModuleDO.SetDOValue(DODefine.AirReset, 0);
                        Mylog.Info("急停触发");
                        throw new Exception("急停触发!");
                    }
                    if (IOModule.GetDIValue(DIDefine.AirWork))
                    {
                        break;
                    }
                    if (timeOut1)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                }
                if (timeOut1)
                {
                    throw new Exception("等待气缸到位超时!");
                }
                Log = "气缸到位";
            }
        }

        public CommandBase StartCommand { get; set; }
        public CommandBase ResetCommand { get; set; }
        public CommandBase UnloadedCommand { get; set; }
        public CommandBase LoadedCommand { get; set; }
        public CommandBase SaveImageCommand { get; set; }
        public CommandBase ResetCountCommand { get; set; }

        private void VmSolution_OnWorkStatusEvent(ImvsSdkDefine.IMVS_MODULE_WORK_STAUS workStatusInfo)
        {
            try
            {
                Mylog.Info($"procid[{workStatusInfo.nProcessID}],status[{workStatusInfo.nWorkStatus}]");
                if (workStatusInfo.nWorkStatus == 0 && workStatusInfo.nProcessID == currentProcId)//为0表示执行完毕，为1表示正在执行；10000表示流程1
                {
                    vmResult = VisionTool.GetGlobalVar("result");
                    visionCompleteEvent?.Set();
                }
            }
            catch (VmException ex)
            {
                Mylog.Error(ex, ex.Message);
            }
        }

        private string _log;
        private string vmResult;
        private bool vmProcHaveExec;
        private uint currentProcId;

        public string Log
        {
            get { return _log; }
            set
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    _log = value;
                    this.DoNotify();
                }));
            }
        }
    }
}